<!--

This sample lists all of the viewer's albums and all of the photos
in each of the albums, then builds a mosaic with all of the photos.

-->
<div id='photos'>Loading...</div>
<script type='text/javascript'>
function init() {
   var req = opensocial.newDataRequest();
   var idspec = opensocial.newIdSpec({'userId':'VIEWER'});
   req.add(req.newFetchAlbumsRequest(idspec),'albums');
   req.send(onLoadAlbums);
}

var albums = [];
var mosaicHtml = [];
var nextAlbumToLoad = 0;

function onLoadAlbums(resp) {
   if (resp.hadError()) {
      debug.say("*** error: " + resp.getErrorMessage());
      try {
         debug.say("*** details: " + resp.get('albums').getErrorMessage());
      } catch (ex) {}
      return;
   }

   debug.say("Response received successfully. Listing albums.");
   albums = resp.get('albums').getData().asArray();
   debug.say(albums.length + " albums returned.");
   requestNextAlbum();
}

function requestNextAlbum() {
   if (nextAlbumToLoad >= albums.length) {
      displayPhotos();
      return;
   }
   debug.say("Requesting album " + nextAlbumToLoad);
   var idspec = opensocial.newIdSpec({'userId':'VIEWER'});
   var albumId = albums[nextAlbumToLoad].getId();
   var req = opensocial.newDataRequest();
   req.add(req.newFetchMediaItemsRequest(idspec, albumId), 'photos');
   req.send(onAlbumArrived);
}

function onAlbumArrived(resp) {
   if (resp.hadError()) {
      debug.say("*** error loading album.");
      return;
   }
   var photos = resp.get('photos').getData().asArray();
   debug.say("Album fetched. Listing photos (" + photos.length + ").");

   for (var i in photos) {
      mosaicHtml.push("<img src='");
      mosaicHtml.push(photos[i].getField(opensocial.MediaItem.Field.THUMBNAIL_URL));
      mosaicHtml.push("'>");
   }

   nextAlbumToLoad++;
   requestNextAlbum();
}

function displayPhotos() {
   debug.say("Done. Displaying.");
   document.getElementById('photos').innerHTML = mosaicHtml.join('');
}

gadgets.util.registerOnLoadHandler(init);

</script>
